'use strict'

let util = require('util');
let fs = require('fs');
let models = require('../modules/models');
let Fiber = require('fibers');

let studentService = require('../modules/services/student');
let checkTimeSetService = require('../modules/services/checktimeset');
let userService = require('../modules/services/user');

let School = models.School;
let Classroom = models.Classroom;
let Grade = models.Grade;
let NatureClass = models.NatureClass;
let Student = models.Student;
let FestivalTip = models.FestivalTip;
let Festival = models.Festival;
let Teacher = models.Teacher;
let Attendance = models.Attendance;
let AttendanceValue = models.AttendanceValue;
let AttendanceStatus = models.AttendanceStatus;
let Track = models.Track;
let TrackType = models.TrackType;

let SchoolDao = models.SchoolDao;
let ClassroomDao = models.ClassroomDao;
let GradeDao = models.GradeDao;
let NatureClassDao = models.NatureClassDao;
let StudentDao = models.StudentDao;
let UserDao = models.UserDao;
let CardDao = models.CardDao;
let CheckTimeSetDao = models.CheckTimeSetDao;
let CheckTimeDao = models.CheckTimeDao;
let FestivalTipDao = models.FestivalTipDao;
let FestivalDao = models.FestivalDao;
let TeacherDao = models.TeacherDao;
let AttendanceDao = models.AttendanceDao;
let AttendanceValueDao = models.AttendanceValueDao;
let TrackDao = models.TrackDao;

function createModels(modelType, modelDao, data) {
    modelDao.remove({});

    let models = data.map(datum => new modelType(datum));
    models.forEach(model => modelDao.create(model));

    return models;
}

function createModelsNoDelete(modelType, modelDao, data) {
    let models = data.map(datum => new modelType(datum));
    models.forEach(model => modelDao.create(model));

    return models;
}

function syncStudents(studentData) {
    Object.keys(studentData).forEach(schoolName => {
        let classList = Object.keys(studentData[schoolName]);
        classList.forEach(className => {
            let csvFilePath = util.format('utils/data/%s/%s/list.csv', schoolName, className);
            let csvFileContent = fs.readFileSync(csvFilePath).toString();
            let students = studentService.fromCsvData(csvFileContent);
            
            students.forEach(student => {
                let existedStudent = StudentDao.findOne({
                    name: student.name.trim()
                });
                if ( !existedStudent ) {
                    console.log('Not existed: ', student.name, student.sid);
                    return;
                }
                existedStudent.sid = student.sid;
                StudentDao.update(existedStudent);
            });
        });
    });
}

let StudentData = {
    '合肥168中学': {
        '高一（1）班': {},
        '高一（27）班': {}
    },
    '合肥市第四十二中学/': { 
        '七（1）班': {}, 
        '七（12）班': {} 
    },
    '合肥市绿怡小学': { 
        '二（2）班': {}, 
        '三（5）班': {} 
    }
};

Fiber(function() {
    syncStudents(StudentData);
    
    process.exit();
}).run();

